<template>
  <section
    class="app-select"
    @click="handleShowPopup"
  >
    <section
      v-if="selectedInfo[props.text]"
      class="selected-label one-line-ellipsis"
    >
      {{ selectedInfo[props.text] }}
    </section>
    <section
      v-else
      class="placeholder one-line-ellipsis"
    >
      {{ placeholder }}
    </section>

    <section class="icon-down-filled-wrap">
      <base-svg-icon icon-class="icon-down-filled" />
    </section>

    <van-popup
      v-model:show="popupDisplay"
      position="bottom"
      safe-area-inset-bottom
      teleport="body"
      :close-on-click-overlay="false"
      :close-on-popstate="true"
    >
      <van-picker
        v-model="selectedValue"
        :columns="options"
        :columns-field-names="props"
        :title="title"
        @cancel="handleHidePopup"
        @confirm="handleSelect"
      />
    </van-popup>
  </section>
</template>

<script setup lang="ts" name="AppSelect">
import { ref, watch } from 'vue';

const theProps = defineProps({
  title: {
    type: String,
    default: '标题',
  },
  modelValue: {
    type: [String, Number],
    default: '',
  },
  placeholder: {
    type: String,
    default: '请选择',
  },
  props: {
    type: Object,
    default: () => ({
      text: 'text',
      value: 'value',
      children: 'children',
    }),
  },
  options: {
    type: Array<TypeObject>,
    default: () => [],
  },
});

const emit = defineEmits(['update:modelValue', 'change']);

const selectedInfo = ref<TypeObject>({});
const selectedValue = ref<any>([]);

const getSelected = (value: string | number, options: TypeObject[]) => {
  const findInfo = options.find((item) => item[theProps.props.value] === value);
  return findInfo;
};

watch(
  () => theProps.modelValue,
  () => {
    const sValue = (getSelected(theProps.modelValue, theProps.options) as any)?.[theProps.props.value] || '';
    selectedValue.value = sValue ? [sValue] : [];
    selectedInfo.value = getSelected(theProps.modelValue, theProps.options) || {};
  },
  {
    immediate: true,
    deep: true,
  }
);

const popupDisplay = ref(false);
const handleShowPopup = () => {
  popupDisplay.value = true;
};

const handleHidePopup = () => {
  popupDisplay.value = false;
};

const handleSelect = ({ selectedOptions }:TypeObject) => {
  const info = selectedOptions[0] || {};
  emit('update:modelValue', info[theProps.props.value]);
  emit('change', info);
  handleHidePopup();
};
</script>

<style lang="scss" scoped>
.app-select {
  position: relative;
  box-sizing: border-box;
  padding-right: var(--#{$ns}-space-size-extra-max);
  padding-left: var(--#{$ns}-space-size-small);
  line-height: var(--#{$ns}-select-height);
  border: 1px solid var(--#{$ns}-border-color);
  border-radius: 4px;

  .icon-down-filled-wrap {
    position: absolute;
    top: 0;
    right: 4px;
    font-size: 24px;
    background-color: #fff;
  }

  .placeholder {
    color: var(--van-text-color-3);
  }
}
</style>
